Server Actions
Server FunctionsをActionsとして呼び出すこと ref
docs
#WIP
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations
Server Actionsのサイズ制限を緩和する
https://ja.react.dev/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024#actions
以前のブログ記事で、クライアントからサーバへデータを送信してデータベース更新やフォーム実装を行うためのソリューションである、Server Action という試みについてお伝えしました。Server Action を開発する中で、これらの API を拡張し、クライアントのみのアプリケーションでのデータ処理にも対応させることにしました。
このより広範な機能の集合は、単に「アクション (Action)」と呼ばれるようになります。アクションにより、<form/> のような DOM 要素に関数を渡すことができるようになります。
単に「Actions」と呼ぶようになるみたいなことが書いてる
<form>のaction属性に対し、Server Functionsを指定できる
これにより、formの実装がJSに依存する部分が減るため、hydrationにおけるuncanny valleyの影響が小さくなる ref
さっさとformがinteractiveになる
また、useTransitionなどを使えば、Client ComponentsからServer Functionsを呼べる
定義の仕方 ref
Server Component内に定義できる
'use server'と指定する必要がある
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#with-server-components
引数と返り値はserializableでないといけない
code:server-component.ts
import kv from './kv';
export default function Page({ params }) {
async function increment() {
'use server';
await kv.incr(post:id:${params.id});
}
return (
<form action={increment}>
<button type="submit">Like</button>
</form>
);
}
別ファイルにも定義できる
'use server'のあるファイル内に定義する
docs
Client Componentから呼べる
useTransitionと併用する(?)
別に併用しなくても使える
code:ts
'use client'
import { useTransition } from 'react'
import { addItem } from '../actions'
function ExampleClientComponent({ id }) {
let isPending, startTransition = useTransition()
return (
<button onClick={() => startTransition(() => addItem(id))}>
Add To Cart
</button>
)
}
Server Mutations
redirect, revalidatePath, revalidateTagを呼び出すServer Actions ref
Form Actions
Web標準の<form> APIに組み込まれたActions
formactoin属性でも使える
useOptimistic
useFormStatus
useActionState
Server Functionsをclientから呼んでるのはどうやってんの?
https://zenn.dev/naofumik/articles/032b3ab4db6c28